package it.polimi.meteocal.web.beans;

import it.polimi.meteocal.ejb.eventmanagement.EventDTO;
import it.polimi.meteocal.ejb.eventmanagement.EventMgr;
import it.polimi.meteocal.ejb.eventmanagement.Event;
import it.polimi.meteocal.ejb.invitationmanagement.Invitation;
import it.polimi.meteocal.ejb.invitationmanager.InvitationMgr;
import it.polimi.meteocal.ejb.notificationmanagement.NotificationMgr;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
 




import org.primefaces.event.ScheduleEntryMoveEvent;
import org.primefaces.event.ScheduleEntryResizeEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultScheduleEvent;
import org.primefaces.model.DefaultScheduleModel;
import org.primefaces.model.ScheduleEvent;
import org.primefaces.model.ScheduleModel;
 
@ManagedBean(name="scheduleView")
@ViewScoped
public class ScheduleView implements Serializable {

	private ScheduleModel eventModel;
 
    private ScheduleEvent event = new DefaultScheduleEvent();
    
    @EJB
    private EventMgr eventMgr;
    
    @EJB
    private InvitationMgr invitationMgr;
    
    @EJB
    private NotificationMgr notificationMgr;
    
    private List<?> events;
    
    private List<?> events2;
    
    private List<Event> list;
    
    private int magic;
 
    @PostConstruct //Post construct cause error 
    public void init() {
    	eventModel = new DefaultScheduleModel();
    	
    	events = eventMgr.findMyEvents();
    	
    	/*DEBUG
    	Event evento = new Event();
    	evento.setName("aa");
    	evento.setDescription("aa");
    	evento.setEventid(1);
    	evento.setBegin(today1Pm());
    	evento.setEnd(today6Pm());
    	*/
    	
    	list = new ArrayList<Event>();
    	
    	for(Object elem: events){
    		list.add((Event) elem);
    	}
    	System.out.println("Contenuto list: "+list.size());
    	
    	//DEBUG
    	//list.add(evento);
    	   	
    	for(int i = 0; i<list.size();i++){
    		//debug
    		System.out.println(">"+list.get(i).getName());
    		//print events
    		Object eventData = new Object();
    		eventData = list.get(i);
    		eventModel.addEvent(new DefaultScheduleEvent(list.get(i).getName(),list.get(i).getBegin(),list.get(i).getEnd(),eventData));
    	}
    }
    
    private Calendar today() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), 0, 0, 0);
 
        return calendar;
    }
    
    private Date today1Pm() {
        Calendar t = (Calendar) today().clone();
        t.set(Calendar.AM_PM, Calendar.PM);
        t.set(Calendar.HOUR, 1);
         
        return t.getTime();
    }
    
    private Date today6Pm() {
        Calendar t = (Calendar) today().clone();
        t.set(Calendar.AM_PM, Calendar.PM);
        t.set(Calendar.HOUR, 6);
         
        return t.getTime();
    }
     
    public Date getRandomDate(Date base) {
        Calendar date = Calendar.getInstance();
        date.setTime(base);
        date.add(Calendar.DATE, ((int) (Math.random()*30)) + 1);    //set random day of month
         
        return date.getTime();
    }
     
    public Date getInitialDate() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), Calendar.FEBRUARY, calendar.get(Calendar.DATE), 0, 0, 0);
         
        return calendar.getTime();
    }
    
    public ScheduleModel getEventModel() {
        return eventModel;
    }
     
    public ScheduleEvent getEvent() {
        return event;
    }
 
    public void setEvent(ScheduleEvent event) {
        this.event = event;
    }
     
    public void addEvent(ActionEvent actionEvent) {
        if(event.getId() == null)
            eventModel.addEvent(event);
        else
            eventModel.updateEvent(event);
         
        event = new DefaultScheduleEvent();
    }
     
    public void onEventSelect(SelectEvent selectEvent) {
        event = (ScheduleEvent) selectEvent.getObject();
    }
     
    public void onDateSelect(SelectEvent selectEvent) {
        event = new DefaultScheduleEvent("", (Date) selectEvent.getObject(), (Date) selectEvent.getObject());
        Date date = event.getStartDate();
        
        Calendar cal = Calendar.getInstance();
        int today = cal.get(Calendar.DAY_OF_MONTH);
        
        //
        System.out.println("today: "+today);
        //
        
        cal.setTime(date);
        
        int selectedDay = cal.get(Calendar.DAY_OF_MONTH)+1;
        
        //
        System.out.println("selected day: "+selectedDay);
        //
        
        magic = selectedDay - today;
        /*if (magic<0){
        	magic=0;
        }*/
        
        //
        System.out.println("magic: "+magic);
        //
    }
     
    public void onEventMove(ScheduleEntryMoveEvent event) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Event moved", "Day delta:" + event.getDayDelta() + ", Minute delta:" + event.getMinuteDelta());
         
        addMessage(message);
    }
     
    public void onEventResize(ScheduleEntryResizeEvent event) {
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Event resized", "Day delta:" + event.getDayDelta() + ", Minute delta:" + event.getMinuteDelta());
         
        addMessage(message);
    }
     
    private void addMessage(FacesMessage message) {
        FacesContext.getCurrentInstance().addMessage(null, message);
    }
    
    public String deleteEvent(Object eventData){
    	Event tmp = new Event();
    	tmp = (Event) eventData;
    	System.out.println("Id evento da cancellare "+tmp.getEventid());
    	eventMgr.delete(tmp.getEventid());
    	
    	events2 = invitationMgr.findEventInvitation(tmp.getEventid());
    	
    	List<Invitation> list2 = new ArrayList<Invitation>();
    	
    	for(Object elem: events2){
    		list2.add((Invitation) elem);
    	}
    	
    	notificationMgr.notifyUsers(list2,"Event "+tmp.getName()+" in date "+tmp.getBegin()+" deleted by organizer please update your schedule");
    	
    	return "personal?faces-redirect=true";
    }
    
    public String modifyEvent(Object eventData){
    	Event tmp = new Event();
    	tmp = (Event) eventData;
    	System.out.println("Id evento da modificare"+tmp.getEventid());
    	EventDTO newevent = new EventDTO();
    	newevent.setBegin(tmp.getBegin());
    	newevent.setDescription(tmp.getDescription());
    	newevent.setEnd(tmp.getEnd());
    	newevent.setInsideOutside(tmp.getInsideOutside());
    	newevent.setName(tmp.getName());
    	newevent.setPlace(tmp.getPlace());
    	eventMgr.modify(newevent, tmp.getEventid());
    	
    	events2 = invitationMgr.findEventInvitation(tmp.getEventid());
    	
    	List<Invitation> list2 = new ArrayList<Invitation>();
    	
    	for(Object elem: events2){
    		list2.add((Invitation) elem);
    	}
    	
    	notificationMgr.notifyUsers(list2,"Event "+newevent.getName()+" in date "+newevent.getBegin()+" modified by organizer please update your schedule: Begin:"+newevent.getBegin()+" End:"+newevent.getEnd()+" Place:"+newevent.getPlace());
    	
    	return "personal?faces-redirect=true";
    }

	public int getMagic() {
		return magic;
	}

	public void setMagic(int magic) {
		this.magic = magic;
	}
    
}